package org.spring.blog.utils;

import io.jsonwebtoken.Claims;
import org.spring.blog.pojo.User;

import java.util.HashMap;
import java.util.Map;

public class ClaimsUtil {

    // 这里的值应该不用与数据库和pojo类保持一致
    // 只有放入jwt和取出的时候保持一致就行
    public static final String ID = "id";
    public static final String USER_NAME = "user_name";
    public static final String ROLES = "roles";
    public static final String AVATAR = "avatar";
    public static final String EMAIL = "email";
    public static final String SIGN = "sign";
    public static final String from = "from";

    private ClaimsUtil() {
    }

    /**
     * 根据用户对象生成claims
     *
     * @param _user 用户对象 (pojo)
     * @param _from 登录设备
     * @return claims对象
     */
    public static Map<String, Object> user2Claims(User _user, String _from) {
        Map<String, Object> claims = new HashMap<>();

        claims.put(ID, _user.getId());
        claims.put(USER_NAME, _user.getUserName());
        claims.put(ROLES, _user.getRoles());
        claims.put(AVATAR, _user.getAvatar());
        claims.put(EMAIL, _user.getEmail());
        claims.put(SIGN, _user.getSign());
        claims.put(from, _from);

        return claims;
    }


    /**
     * 根据claims 对象生成 user 对象
     *
     * @param _claims claims 对象
     * @return user 对象（pojo）
     */
    public static User claims2User(Claims _claims) {

        return new User().setId((String) _claims.get(ID))
                .setUserName((String) _claims.get(USER_NAME))
                .setAvatar((String) _claims.get(AVATAR))
                .setEmail((String) _claims.get(EMAIL))
                .setSign((String) _claims.get(SIGN))
                .setRoles((String) _claims.get(ROLES));
    }
}
